/**
 * Created by lional on 16/10/2.
 */

jGame.ListView = ccui.ListView.extend(/** @lends jGame.ListView# */{

    _data:null,
    _controller:null,
    _defaultItem:null,
    _defaultItemJson:null,
    _defaultEmptyText:null,
    
    ctor: function () {
        this._super();
        //cc.log("jGame.ListView#ctor()");
    },

    setController: function(controller){
        this._controller = controller;
    },

    getController: function(){
        return this._controller;
    },

    setItemFromJsonFile: function (json_file_path) {
        if(!json_file_path) return;

        var itemNode = jGame.load(json_file_path, "res/");
        if(itemNode && itemNode.node) {
            var default_item = new jGame.Layout();
            default_item.setContentSize(itemNode.node.getContentSize());
            while (itemNode.node.getChildrenCount() > 0) {
                var child = itemNode.node.getChildren()[0];
                child.removeFromParent();
                default_item.addChild(child);
            }
            this._defaultItem = default_item;
        }
    },

    setItemJsonFile: function (json_file_path) {
        this._defaultItemJson = json_file_path;
    },

    setEmptyText: function (text) {
        this._defaultEmptyText = text;
        this._showEmptyText();
    },

    _showEmptyText: function () {
        if(this.getItems().length == 0) {
            var defaultEmptyText = this.getChildByName("defaultEmptyText");
            if(!defaultEmptyText) {
                if(typeof this._defaultEmptyText === "string") {
                    var Panel = new jGame.Layout();
                    Panel.setContentSize(this.width, this.height);
                    var Text = new jGame.Text(this._defaultEmptyText, "Helvetica", 48);
                    Panel.addChild(Text);
                    Panel.setName("defaultEmptyText");
                    Text.setAnchorPoint(0.5, 0.5);
                    Text.setPosition(this.width/2, this.height/2);
                    this.addChild(Panel);
                }
            }
        }else {
            var defaultEmptyText = this.getChildByName("defaultEmptyText");
            if(defaultEmptyText) {
                defaultEmptyText.removeFromParent();
            }
        }
    },

    // setDefaultItemData: function (data, callback, path) {
    //
    //     this.removeAllChildren();
    //
    //     this._data = data;
    //     if(typeof path === "string")this._defaultItemJson = path;
    //     if(!this._defaultItemJson || !data) return;
    //     var count = 0;
    //     for(var index in data) {
    //         var itemNode = jGame.load(this._defaultItemJson, "res/");
    //         if(itemNode && itemNode.node) {
    //             var default_item =  new jGame.Layout();
    //             default_item.setTag(count);
    //             default_item.setContentSize(itemNode.node.getContentSize());
    //             while (itemNode.node.getChildrenCount() > 0) {
    //                 var child = itemNode.node.getChildren()[0];
    //                 child.removeFromParent();
    //                 default_item.addChild(child);
    //             }
    //             jGame.setAllChildrenController(default_item, this._controller);
    //             if(default_item.width == 0 || default_item.height == 0) {
    //                 cc.log("Warning : list item width or height is 0.");
    //             }
    //             this.pushBackCustomItem(default_item);
    //             if(typeof callback === "function") {
    //                 callback(count, default_item, index);
    //             }
    //             count++;
    //         }
    //     }
    //     this._showEmptyText();
    // },

    setDefaultItemData: function (data, callback, path) {
        this._data = data;
        if(typeof path === "string") {
            this.setItemFromJsonFile(path);
        }else if(path instanceof ccui.Widget){
            this._defaultItem = path;
        }
        if(!this._defaultItem || !data) return;
        var count = 0;
        for(var index in data) {
            var default_item =  jGame.clone(this._defaultItem);
            default_item.setTag(count);
            jGame.setAllChildrenController(default_item, this._controller);
            if (default_item.width == 0 || default_item.height == 0) {
                cc.log("Warning : list item [" + index + "] width or height is 0.");
            }
            this.pushBackCustomItem(default_item);
            if(typeof callback === "function") {
                callback(count, default_item, index);
            }
            count++;
        }
    },

    setSelectCallbackName: function (callBackName) {
        var widget = this;
        var callBack = function(sender, type){
            if(typeof widget["_controller"] === "object" && typeof widget["_controller"][callBackName] === "function"){
                widget["_controller"][callBackName](sender, type);
                if(typeof widget["_controller"]["trace"] === "function")widget["_controller"]["trace"](sender, type);
            }
            else if(typeof widget[callBackName] === "function")
                widget[callBackName](sender, type);
        };
        this.addEventListener(callBack, this);
    },

});

jGame.CustomTableViewCell = cc.TableViewCell.extend({
    draw:function (ctx) {
        this._super(ctx);
    }
});

jGame.TableView = ccui.Layout.extend(/** @lends jGame.TableView# */{

    _tableView: null,
    _data:null,
    _dataKeys:null,
    _defaultItem:null,
    _defaultItemJson:null,
    _defaultEmptyText:null,
    _selectCallback:null,
    _tableCellCallback:null,

    ctor: function () {
        this._super();
        cc.log("jGame.TableView#ctor()");
    },

    _initTableView: function (widget, height) {
        var locWidth = widget;
        var locHeight = height;
        if (widget === undefined) {
            locWidth = 0;
            locHeight = 0;
        }else  if (height === undefined) {
            locWidth = widget.width;
            locHeight = widget.height;
        }

        var tbView = this.getChildByName("_tableView");
        if(tbView) {
            this.removeChild(tbView);
        }
        this._tableView = new cc.TableView(this, cc.size(locWidth, locHeight));
        this._tableView.setName("_tableView");
        this._tableView.setDelegate(this);
        this._tableView.setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN);
        this.addChild(this._tableView);
        this._tableView.reloadData();
        this._tableView.setTouchEnabled(true);
        //this.setOneByOneCallbackName("onTableViewTouchBegan", "onTableViewTouchMoved", "onTableViewTouchEnded", "onTableViewTouchCancelled");
    },

    setItemFromJsonFile: function (json_file_path) {
        if(!json_file_path) return;

        var itemNode = jGame.load(json_file_path, "res/");
        if(itemNode && itemNode.node) {
            var default_item = new jGame.Layout();
            default_item.setContentSize(itemNode.node.getContentSize());
            while (itemNode.node.getChildrenCount() > 0) {
                var child = itemNode.node.getChildren()[0];
                child.removeFromParent();
                default_item.addChild(child);
            }
            this._defaultItem = default_item;
        }
    },

    setItemJsonFile: function (json_file_path) {
        this._defaultItemJson = json_file_path;
    },

    setEmptyText: function (text) {
        this._defaultEmptyText = text;
        this._showEmptyText();
    },

    _showEmptyText: function () {
        if(!this._dataKeys || this._dataKeys.length == 0) {
            var defaultEmptyText = this.getChildByName("defaultEmptyText");
            if(!defaultEmptyText) {
                if(typeof this._defaultEmptyText === "string") {
                    var Panel = new jGame.Layout();
                    Panel.setContentSize(this.width, this.height);
                    var Text = new jGame.Text(this._defaultEmptyText, "Helvetica", 48);
                    Panel.addChild(Text);
                    Panel.setName("defaultEmptyText");
                    Text.setAnchorPoint(0.5, 0.5);
                    Text.setPosition(this.width/2, this.height/2);
                    this.addChild(Panel);
                }
            }
        }else {
            var defaultEmptyText = this.getChildByName("defaultEmptyText");
            if(defaultEmptyText) {
                defaultEmptyText.removeFromParent();
            }
        }
    },

    setDefaultItemData: function (data, callback, path) {

        this.removeAllChildren();

        this._data = data;
        this._dataKeys = [];
        var count = 0;
        for(var index in data) {
            this._dataKeys[count] = index;
            count++;
        }
        this._tableCellCallback = callback;
        if(typeof path === "string")this._defaultItemJson = path;
        
        this._tableView.reloadData();
        this._showEmptyText();
    },

    setSelectCallbackName: function (callBackName) {
        var widget = this;
        this._selectCallback = function(sender, type){
            if(typeof widget["_controller"] === "object" && typeof widget["_controller"][callBackName] === "function"){
                widget["_controller"][callBackName](sender, type);
                if(typeof widget["_controller"]["trace"] === "function")widget["_controller"]["trace"](sender, type);
            }
            else if(typeof widget[callBackName] === "function")
                widget[callBackName](sender, type);
        };
    },

    scrollViewDidScroll:function (view) {

    },

    scrollViewDidZoom:function (view) {

    },

    tableCellTouched:function (table, cell) {
        cc.log("cell touched at index: " + cell.getIdx());
        if(this._selectCallback) {

        }
    },

    tableCellTouched2:function () {
        cc.log("cell touched at index: ");
    },

    tableCellSizeForIndex:function (table, idx) {
        if (this._defaultItemJson) {
            var itemNode = jGame.load(this._defaultItemJson, "res/");
            if(itemNode && itemNode.node) {
                return itemNode.node.getContentSize();
            }
        }
        return cc.size();
    },

    tableCellAtIndex:function (table, idx) {
        var count = parseInt(idx);
        var cell = table.dequeueCell();
        if (!cell) {
            cell = new jGame.CustomTableViewCell();
            var itemNode = jGame.load(this._defaultItemJson, "res/");
            if(itemNode && itemNode.node) {
                var default_item = new jGame.Layout();
                default_item.setTag(count);
                default_item.setContentSize(itemNode.node.getContentSize());
                while (itemNode.node.getChildrenCount() > 0) {
                    var child = itemNode.node.getChildren()[0];
                    child.removeFromParent();
                    default_item.addChild(child);
                }
                jGame.setAllChildrenController(default_item, this._controller);
                if (default_item.width == 0 || default_item.height == 0) {
                    cc.log("Warning : list item width or height is 0.");
                }
                cell.addChild(default_item);
                if(this._tableCellCallback) {
                    this._tableCellCallback(count, default_item, this._dataKeys[count]);
                }
            }
        } else {
            var default_item = cell.getChildren()[0];
            if(this._tableCellCallback) {
                this._tableCellCallback(count, default_item, this._dataKeys[count]);
            }
        }

        return cell;
    },

    numberOfCellsInTableView:function (table) {
        return this._dataKeys?this._dataKeys.length:0;
    },

    setDirection: function (directionType) {
        if(directionType == ccui.ScrollView.DIR_VERTICAL) {
            this._tableView.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
        }else {
            this._tableView.setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL);
        }
    },

    setGravity: function (gravity) {
        //todo 设置gravity
    },

    setBounceEnabled: function (bounceEnabled) {
        //todo 设置反弹
    },

    setItemsMargin: function (itemMargin) {
        //todo 设置item间隔
    },

    setInnerContainerSize: function (widget, height) {
        this._initTableView(widget, height);
    },

    removeAllChildren: function (cleanup) {
        for(var index in this.getChildren()) {
            var child = this.getChildren()[index];
            if(child.getName() != "_tableView") {
                this.removeChild(child, cleanup);
            }
        }
    },

});